package org.qhhc.singleton;

import java.io.*;

public class SingletonWithHolderAndReflectionProtection_eh implements Serializable {
    private static final long serialVersionUID = 1L;
    // 私有构造函数
    private SingletonWithHolderAndReflectionProtection_eh() {
        // 防止通过反射创建多个实例
        if (Holder.INSTANCE != null) {
            throw new IllegalStateException("Singleton instance already exists.");
        }
    }

    // 静态内部类作为Holder
    private static class Holder {
        // 静态常量，存储单例实例
        private static final SingletonWithHolderAndReflectionProtection_eh INSTANCE =
                new SingletonWithHolderAndReflectionProtection_eh();
    }

    // 公共的获取单例实例的方法
    public static SingletonWithHolderAndReflectionProtection_eh getInstance() {
        return Holder.INSTANCE;
    }
    // 新增 readResolve 方法
    private Object readResolve() {
        return Holder.INSTANCE;
    }
    public static void main(String[] args) {
        // 序列化单例对象到文件
        try{
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton.ser"));
            oos.writeObject(SingletonWithHolderAndReflectionProtection_eh.getInstance());
            oos.close();

            // 反序列化两次
            ObjectInputStream ois1 = new ObjectInputStream(new FileInputStream("singleton.ser"));
            SingletonWithHolderAndReflectionProtection_eh instance1 = (SingletonWithHolderAndReflectionProtection_eh) ois1.readObject();

            ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("singleton.ser"));
            SingletonWithHolderAndReflectionProtection_eh instance2 = (SingletonWithHolderAndReflectionProtection_eh) ois2.readObject();

            System.out.println(instance1 == instance2); // 输出 false
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}


